package com.lzx.iteam.contactssearch;

import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.text.TextUtils;
import com.lzx.iteam.contactssearch.conversion.Addressbook;
import com.lzx.iteam.contactssearch.conversion.PinyinSearch;
import com.lzx.iteam.util.Constants;
import com.lzx.iteam.util.PhoneNumberArea;
import com.lzx.iteam.util.PreferenceUtil;
import com.lzx.iteam.util.StringUtil;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;

/**
 * Created by xuepengju on 14-7-16.
 */
public class BuildContacts {

    private Context mContext;
    private PreferenceUtil mPreferenceUtil;


    public BuildContacts(Context context) {
        mContext = context;
        mPreferenceUtil = PreferenceUtil.getInstance(context);
    }


    public void startBuildContacts(long contactId){
        generatePinyinIndex(contactId);
        buildContact(contactId);
    }

    private void generatePinyinIndex(long contactId) {
        if (contactId == -1) {
            return;
        }
        Uri contactUri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, contactId);
        String dataDir = ContactsContract.Contacts.Data.CONTENT_DIRECTORY;
        Uri methodUri = Uri.withAppendedPath(contactUri, dataDir);
        boolean ifShowPeopleNoPhone = mPreferenceUtil.getBoolean(PreferenceUtil.SHOW_PEOPLE_NO_PHONENUMBER, false);
        Cursor c = mContext.getContentResolver().query(methodUri, ContactsDBReader.CONTACTS_SUMMARY_PROJECTION,
                ifShowPeopleNoPhone ? null : Constants.CLAUSE_ONLY_PHONES, null, null);

        PinyinSearch mPinyinSearch = PinyinSearch.getInstance(mContext);
//        mPinyinSearch.clearMemoryData();
        if (mPinyinSearch.mHanziPinyin == null) {
            mPinyinSearch.mHanziPinyin = StringUtil.getHanziPinyin(mContext, null);
        }
        while (c.moveToNext()) {
            String displayName = c.getString(ContactsDBReader.SUMMARY_NAME_COLUMN_INDEX);
            int contactedNumber = c.getInt(ContactsDBReader.SUMMARY_TIMES_CONTACTED_COLUMN_INDEX);
            int hasPhoneNumber = c.getInt(ContactsDBReader.SUMMARY_HAS_PHONE_COLUMN_INDEX);

            if (hasPhoneNumber == 1) {
                if (StringUtil.isEmpty(displayName)) {
                    displayName = mContext.getString(com.lzx.iteam.R.string.unknown);
                }
                mPinyinSearch.addPinyinDict(displayName, contactId, null, contactedNumber, hasPhoneNumber == 1 ? true : false);
            } else {
                if (ContactsDBReader.checkContactNameExistByID(mContext.getContentResolver(), contactId)) {
                    mPinyinSearch.addPinyinDict(displayName, contactId, null, contactedNumber, hasPhoneNumber == 1 ? true : false);
                }
            }
        }
        mPinyinSearch.mHanziPinyin = null;
    }


    private void buildContact(long contactId){
        if(contactId == -1) return;

        ArrayList<String> phoneNumArr = new ArrayList<String>();
        ArrayList<String> phoneNumberAreaArr = new ArrayList<String>();
        HashSet<String> groupIdSet = new HashSet<String>();
        StringBuilder orgnization = new StringBuilder();
        StringBuilder emailString = new StringBuilder();
        StringBuilder noteString = new StringBuilder();

        String fullName = null;
        String organizationName = null;
        String email = null;
        String note = null;
        StringBuffer wx_ids = new StringBuffer();

        long rawId = 0L;
        long photoId = 0L;
        long version = 0L;
        int type = 0;

        Uri contactUri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, contactId);
        String dataDir = ContactsContract.Contacts.Data.CONTENT_DIRECTORY;
        Uri methodUri = Uri.withAppendedPath(contactUri, dataDir);
        PinyinSearch mPinyinSearch = PinyinSearch.getInstance(mContext);
        if (mPinyinSearch.mFirstLetterStr == null) {
            mPinyinSearch.mFirstLetterStr = StringUtil.getFirstLetterStr(mContext);
        }
        Cursor c = null;
        try {
            c = mContext.getContentResolver().query(methodUri,
                    ContactsDBReader.DATA_PROJECTION, null, null, null);
        } catch (IllegalArgumentException e) {
            if (c != null) {
                c.close();
            }
        }

        if (c != null) {
            try {
                boolean isTrue = c.moveToFirst();
                while (isTrue) {
                    String mime = c.getString(c.getColumnIndex(ContactsContract.Data.MIMETYPE));
                    if (ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE.equals(mime)) {
                        String phoneNumber = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                        phoneNumArr.add(phoneNumber);
                        /*PhoneNumberArea phoneNumberArea = PhoneNumberArea.getInstance(mContext.getApplicationContext());
                        String area = phoneNumberArea.getArea(phoneNumber,
                                false);
                        if (!StringUtil.isEmpty(area)) {
                            if (!phoneNumberAreaArr.contains(area)) {
                                phoneNumberAreaArr.add(area);
                            }
                        }*/
                    } else if (ContactsContract.CommonDataKinds.GroupMembership.CONTENT_ITEM_TYPE.equals(mime)) {
                        String groupId = c.getString(c
                                .getColumnIndex(ContactsContract.CommonDataKinds.GroupMembership.GROUP_ROW_ID));
                        if (groupId != null && ContactsDBReader.mGroupList != null) {
                            ContactsDBReader.GroupInfo group = ContactsDBReader.mGroupList.get(groupId);
                            if (group != null) {
                                groupIdSet.add(groupId);
                            }
                        }

                    } else if (ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE.equals(mime)) {
                        emailString.append(email);
                        emailString.append(",");

                    } else if (ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE.equals(mime)) {
                        String company = c.getString(c
                                .getColumnIndex(ContactsContract.CommonDataKinds.Organization.COMPANY));// item.getPrimaryData();
                        String post = c.getString(c
                                .getColumnIndex(ContactsContract.CommonDataKinds.Organization.TITLE));// item.getPrimaryData();
                        if (!StringUtil.isEmpty(post)) {
                            orgnization.append(post);
                        }
                        if (!StringUtil.isEmpty(company)) {
                            if (orgnization.length() > 0) {
                                orgnization.append(",");
                            }
                            orgnization.append(" " + company);
                        }
                    } else if (ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE.equals(mime)) {
                        noteString.append(c.getString(c.getColumnIndex(
                                ContactsContract.CommonDataKinds.Note.NOTE))).append(',');
                    }else if(Constants.WX_CHAT.equals(mime)){
                        String wx_tag = c.getString(c.getColumnIndex(ContactsContract.Data.DATA2));
                        String wx_type = c.getString(c.getColumnIndex(ContactsContract.Data.DATA3));
                        if ("微信".equals(wx_tag) && "聊天".equals(wx_type)) {
                            wx_ids.append(""+contactId);
                            wx_ids.append(",");
                        }
                    }else if (ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE.equals(mime)) {
                        fullName = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME));
                    }
                    isTrue = c.moveToNext();
                }

                if(StringUtil.isEmpty(wx_ids.toString())){
                    mPreferenceUtil.delete(Constants.WX_IDS_SET);
                }else{
                    mPreferenceUtil.save(Constants.WX_IDS_SET, wx_ids.toString());
                }
            }  catch (Exception e) {
                e.printStackTrace();
            } finally {
                c.close();
            }
        }
        /*******************************************************************/
        if (orgnization != null) {
            organizationName = orgnization.toString();
        }

        if (emailString != null) {
            email = emailString.toString();
        }

        StringBuilder fuzzyStringSb = new StringBuilder();
        if (phoneNumberAreaArr != null) {
            for (String areaElement : phoneNumberAreaArr) {
                if (!StringUtil.isEmpty(areaElement)) {
                    fuzzyStringSb.append(StringUtil.trasferDisplayName(mContext,
                            new StringBuffer(areaElement), mPinyinSearch.mFirstLetterStr));
                    fuzzyStringSb.append(",");
                }
            }
        }
        if (!StringUtil.isEmpty(fullName)) {
            StringBuffer sb = new StringBuffer(fullName);
            fuzzyStringSb.append(StringUtil.trasferDisplayName(mContext, sb,
                    mPinyinSearch.mFirstLetterStr));
            fuzzyStringSb.append(",");
        }

        if (!StringUtil.isEmpty(organizationName)) {
            StringBuffer sb = new StringBuffer(organizationName);
            fuzzyStringSb.append(StringUtil.trasferGOJ(mContext, sb,
                    mPinyinSearch.mFirstLetterStr));
        }

        if (phoneNumberAreaArr != null) {
            for (String areaElement : phoneNumberAreaArr) {
                String fuzzyArea = StringUtil.trasferDisplayName(mContext,
                        new StringBuffer(areaElement), mPinyinSearch.mFirstLetterStr);
                fuzzyArea += ",";
                fuzzyStringSb.insert(0, fuzzyArea);
            }
        }

        if (noteString != null) {
            note = noteString.toString();
        }

        if (!TextUtils.isEmpty(note)) {
            fuzzyStringSb.append(StringUtil.trasferDisplayName(mContext,
                    new StringBuffer(note),
                    mPinyinSearch.mFirstLetterStr));
        }

//            String fuzzy = StringUtil.trim(fuzzyStringSb.toString());
        String fuzzy = fuzzyStringSb.toString().replaceAll(StringUtil.SAPCE_REGEX, "");
        mPinyinSearch.addFuzzyString(contactId, fuzzy);


        if (type != Constants.TYPE_EQUAL) {
//                Log.i(TAG, "need insert, index:" + (index++));
            Addressbook.Person.Builder builder = Addressbook.Person.newBuilder();
            if(!StringUtil.isEmpty(fullName)){
                builder.setDisplayName(fullName);
            }else{
                builder.setDisplayName("");
            }

            builder.setPhotoId(photoId);
            builder.setRawId(rawId);
            if (organizationName == null) {
                organizationName = "";
            }
            builder.setOrganization(organizationName);

            if (email == null) {
                email = "";
            }
            builder.setEmail(email);
            builder.setFuzzyString(fuzzy);
            builder.setContactedNumber(0);
            builder.setVersion(version);
            builder.setNote(note);

            if (phoneNumArr != null) {
                for (String phoneElement : phoneNumArr) {
                    if (!StringUtil.isEmpty(phoneElement)) {
                        builder.addPhone(Addressbook.Person.PhoneNumber.newBuilder()
                                .setNumber(phoneElement));
                    }
                }
            }

            if (phoneNumberAreaArr != null) {
                for (String areaElement : phoneNumberAreaArr) {
                    if (!StringUtil.isEmpty(areaElement)) {
                        builder.addPhoneNumberArea(Addressbook.Person.PhoneNumberArea.newBuilder().setArea(
                                areaElement));
                    }
                }
            }

            if (groupIdSet != null) {
                Iterator<String> it = groupIdSet.iterator();
                while (it.hasNext()) {
                    String groupId = it.next();
                    builder.addGroupIdSet(Addressbook.Person.GroupIdSet.newBuilder().setGroupId(
                            Long.parseLong(groupId)));
                }
            }
            Addressbook.Person person = builder.build();

            mPreferenceUtil.deletePerson(contactId);
            mPreferenceUtil.savePerson(contactId, person);
        }

        Intent intent = new Intent("broadcast_status_change");
        mContext.sendBroadcast(intent);
    }
}